//
//  CommentController.m
//  yuikemall
//
//  Created by yuike5 yuike5 on 12-2-22.
//  Copyright (c) 2012年 yuike. All rights reserved.
//
#import "YkNetWork.h"
#import "CommentController.h"
#import "header.h"

@implementation CommentController
@synthesize vCell;
@synthesize vText;
@synthesize vLabel;
@synthesize vAtButton;
@synthesize vEmotionButton;
@synthesize vQuickButton;

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        [[NSBundle mainBundle] loadNibNamed:@"CommentController" owner:self options:nil];
        // Custom initialization
        self.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc] initWithTitle:@"取消" 
                                                                                  style:UIBarButtonItemStyleBordered 
                                                                                 target:self 
                                                                                 action:@selector(cancelBarBtnPressed)] autorelease];
        self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithTitle:@"发表" 
                                                                                   style:UIBarButtonItemStyleBordered 
                                                                                  target:self 
                                                                                  action:@selector(sendBarBtnPressed)] autorelease];
        
        [self.vAtButton addTarget:self action:@selector(theButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
        [self.vEmotionButton addTarget:self action:@selector(theButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
        [self.vQuickButton addTarget:self action:@selector(theButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
        
        [vAtButton setBackgroundImage:[UIImage imageNamed:@"weibo_at"] forState:UIControlStateNormal];
        [vAtButton setBackgroundImage:[UIImage imageNamed:@"weibo_at2"] forState:UIControlStateHighlighted];
        [vEmotionButton setBackgroundImage:[UIImage imageNamed:@"weibo_emotion"] forState:UIControlStateNormal];
        [vEmotionButton setBackgroundImage:[UIImage imageNamed:@"weibo_emotion2"] forState:UIControlStateHighlighted];
        
        [vQuickButton setBackgroundImage:[UIImage imageNamed:@"weibo_suggest"] forState:UIControlStateNormal];
        [vQuickButton setBackgroundImage:[UIImage imageNamed:@"weibo_suggest2"] forState:UIControlStateHighlighted];
        
        
        [vText becomeFirstResponder]; 
        mWeiboAtController = [[WeiboAtController alloc] init];
        mWeiboEmotionController = [[WeiboEmotionController alloc] init];
        mWeiboSuggestionController = [[WeiboSuggestionController alloc] initWithStyle:UITableViewStylePlain];
    }
    return self;
}

-(void) setWeiboSuggests:(NSArray*)array_
{
    mWeiboSuggestionController.array = array_;
    [mWeiboSuggestionController setCallback:self sel:@selector(theWeiboSuggestCallback:)];
}

-(void) cancelBarBtnPressed
{
    if (vText.text.length <= 0) {
        [[self parentViewController] dismissModalViewControllerAnimated:YES];
        [callback theCommentControllerDismiss:self weiboid:weibo.theSnsId sendx:false];
        return;
    }
    
    // 必须保证只能出现一个，否则会发生 崩溃
    UIActionSheet* sheet = [[UIActionSheet alloc] 
                            initWithTitle:nil  
                            delegate:self  
                            cancelButtonTitle:nil  
                            destructiveButtonTitle:nil  
                            otherButtonTitles:@"确认要取消", nil];
    [sheet autorelease];
    [sheet showFromBarButtonItem:self.navigationItem.leftBarButtonItem animated:YES];
    self.navigationItem.leftBarButtonItem.enabled = false;
    self.navigationItem.rightBarButtonItem.enabled = false;
}
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 0) {
        [[self parentViewController] dismissModalViewControllerAnimated:YES];
        [callback theCommentControllerDismiss:self weiboid:weibo.theSnsId sendx:false];
    } else {
        self.navigationItem.leftBarButtonItem.enabled = true;
        self.navigationItem.rightBarButtonItem.enabled = true;
    }
}
- (void)actionSheet:(UIActionSheet *)actionSheet didDismissWithButtonIndex:(NSInteger)buttonIndex {
    self.navigationItem.leftBarButtonItem.enabled = true;
    self.navigationItem.rightBarButtonItem.enabled = true;
}


#define HUD_ID 6498113
-(void) sendBarBtnPressed
{
    NSString* text = self.vText.text.strip;
    if (!text || text.length<=0) {
        [self.view makeToast:@"评论内容为空"];
        return;
    }
    [weibo comment:self idx:node.idx comment:text];
    
    
    self.navigationItem.leftBarButtonItem.enabled = NO;
    self.navigationItem.rightBarButtonItem.enabled = NO;
    
    MBProgressHUD* HUD = [[[MBProgressHUD alloc] initWithView:self.navigationController.view] autorelease];
    HUD.tag = HUD_ID;    
    [self.navigationController.view addSubview:HUD];
    [HUD show: YES];
}
-(void) createCommentError:(WeiboBase*)weibo reason:(NSString*)reason
{
    NSString* info = @"评论失败";
    if (reason && reason.length!=0) {
        info = [info stringByAppendingString:@"\n"];
        info = [info stringByAppendingString:reason.strip];
    }
    [self.view makeToast:info duration:TOAST_DRRATION_LONG];

    self.navigationItem.leftBarButtonItem.enabled = YES;
    self.navigationItem.rightBarButtonItem.enabled = YES;
    MBProgressHUD* HUD = (MBProgressHUD*) [self.navigationController.view viewWithTag:HUD_ID];
    [HUD hide: YES];
}
-(void) createCommentCallback:(WeiboBase*)weibo idx:(long long)idx result:(WeiboCommentNode*)result
{
    MBProgressHUD* HUD = (MBProgressHUD*) [self.navigationController.view viewWithTag:HUD_ID];
    [HUD hide: YES];
    [self performSelector:@selector(dismissSelfx) withObject:nil afterDelay:0.8f];
}
-(void) dismissSelfx
{
    [[self parentViewController] dismissModalViewControllerAnimated:YES];
    [callback theCommentControllerDismiss:self weiboid:weibo.theSnsId sendx:true];
}

-(void) setCallback:(id<CommentControllerCallback>)callback_ {
    callback = callback_;
}



-(void) theButtonPressed:(id)sender
{
    UIButton* button = nil;
    UIViewController* ctrl = nil;
    if (sender == self.vAtButton) {
        button = self.vAtButton;
        ctrl = mWeiboAtController;
    } else if (sender == self.vEmotionButton) {
        button = self.vEmotionButton;
        ctrl = mWeiboEmotionController;
    } else if (sender == self.vQuickButton) {
        button = self.vQuickButton;
        ctrl = mWeiboSuggestionController;
    } else {
        return;
    }
    
    if (!mPopoverController)
        mPopoverController = [[UIPopoverController alloc] initWithContentViewController:ctrl];
    [mPopoverController setContentViewController:ctrl animated:true];
    
    [mPopoverController setPopoverContentSize:CGSizeMake(240, 320)];
    
    CGRect temp = [button frameInAncestorView:self.view];
    [mPopoverController presentPopoverFromRect:temp
                                       inView:self.view 
                     permittedArrowDirections:UIPopoverArrowDirectionLeft
                                     animated:YES];
}

-(void) setWeibo:(int)weibo_ node:(WeiboNode*)node_
{
    if (weibo_ == SNS_ID_SINA_WEIBO) {
        [weibo release];
        weibo = [[SinaWeibo alloc ] init ];
    }
//    else if (weibo_ == SNS_ID_TENC_WEIBO) {
//        [weibo release];
//        weibo = [[TencWeibo alloc  ] init ];
//    } 
    else {
        assert( false);
    }
    
    node = [node_ retain];
    
    [mWeiboAtController setWeiboId: weibo_ callback:self sel:@selector(theWeiboAtCallback:)];
    [mWeiboEmotionController setWeibo:weibo.emotions callback:self sel:@selector(theWeiboEmotionCallback:)];
    [vLabel setText: node.text];
}

-(void) theWeiboEmotionCallback: (WeiboEmotion*) e
{    
    [vText insertString:e.phrase leftSpace:true rightSpace:true];
    [mPopoverController dismissPopoverAnimated:true];
}

-(void) theWeiboAtCallback: (WeiboUserNode*)user
{
    [vText insertString:[NSString stringWithFormat:@"@%@", user.atName] leftSpace:true rightSpace:true];
    [mPopoverController dismissPopoverAnimated:true];
}
-(void) theWeiboSuggestCallback:(NSString*)str
{
    // BOOL startSpace = [str startswith:@" "];//
    // BOOL endSpace = [str endswith:@" "]; // 比如@谁，后面必须有空格
    
    str = [str replace:@"\r" with:@" "];
    str = [str replace:@"\n" with:@" "];
    while ([str rangeOfString:@"  "].length != 0) {
        str = [str replace:@"  " with:@" "];
    }
    // str = str.strip;
    [vText insertString:str leftSpace:false rightSpace:false];
    [mPopoverController dismissPopoverAnimated:true];
}


-(void) dealloc
{
    [vText release];
    [vCell release];
    [vLabel release];
    [vAtButton release];
    [vEmotionButton release];
    [vQuickButton release];
    
    [mPopoverController release];
    [mWeiboAtController release];
    [mWeiboEmotionController release];
    [mWeiboSuggestionController release];
    
    [weibo release];
    [node release];
    
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
    DEF_didReceiveMemoryWarning;
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];

    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
 
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
    self.title = @"评论";
    self.tableView.scrollEnabled = FALSE;
    [YkNetWork checkNetworkAvailable:self.view];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
	return YES;
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    return 1;
}

-(void) updateButtonsLayout {
    
    CGRect kt = vEmotionButton.frame;
    kt.origin.x += kt.size.width + 2;
    
    if (!vAtButton.hidden) {
        vAtButton.frame = kt;
        kt.origin.x += kt.size.width + 2;
    }
    if (!vQuickButton.hidden) {
        vQuickButton.frame = kt;
    }
}

#define TABLE_VIEWCELL_TXT   1001
#define TABLE_VIEWCELL_TXT_BAK   1004
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = nil;//[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    //if (cell == nil) {
    //    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    //}
    
    cell = self.vCell;
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone]; // 必须，否则text view 可能丢失指针。
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.frame = [tableView rectForRowAtIndexPath:indexPath];
    
    CGRect frame = cell.frame;
    CGSize size = frame.size;
    int width = 480;//size.width;
    int height = size.height;
    const int border = 5;
    
    vText.frame = CGRectMake(border, border,
                             width - border - border,
                             height - border - border - 1);
    
    int labelHeight = 24;
    frame = vText.frame;
    frame.origin.y += frame.size.height - labelHeight;
    frame.size.height = labelHeight;
    vLabel.frame = frame;
    //vLabel.backgroundColor = [UIColor redColor];
    
    if (true) {
        int cpsHeight = labelHeight;
        {
            CGRect kt = CGRectMake(border, border, width-border*2, height-border*2);
            CGSize imageSize = [UIImage imageNamed:@"weibo_at"].size;
            
            kt.origin.y += kt.size.height - imageSize.height - cpsHeight;
            kt.size = imageSize;
            
            vEmotionButton.frame = kt;
            vQuickButton.hidden = !mWeiboSuggestionController.needDisplay;
            [self updateButtonsLayout];
        }
    }    
    
    // 设置背景
    UIView* textv = [vCell viewWithTag:TABLE_VIEWCELL_TXT];
    UIView* textf = [vCell viewWithTag:TABLE_VIEWCELL_TXT_BAK];
    CGRect temp = textv.frame;
    // 橡树微调
    temp.size.width += -1; // 
    textf.frame = temp;
    textf.hidden = true;
    return cell;
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{    
    int section = indexPath.section;
    int row = indexPath.row;
    if (section == 0 && row == 0) {
        return 240;
    }
    return 50;
}

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Navigation logic may go here. Create and push another view controller.
    /*
     <#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:@"<#Nib name#>" bundle:nil];
     // ...
     // Pass the selected object to the new view controller.
     [self.navigationController pushViewController:detailViewController animated:YES];
     [detailViewController release];
     */
}

@end
